/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import org.aswing.ASColor;
import org.aswing.ASWingUtils;
import org.aswing.border.EmptyBorder;
import org.aswing.BorderLayout;
import org.aswing.geom.Point;
import org.aswing.Insets;
import org.aswing.JButton;
import org.aswing.JCheckBox;
import org.aswing.JFrame;
import org.aswing.JLabel;
import org.aswing.JPanel;
import org.aswing.JTextField;
import org.aswing.SoftBoxLayout;
import org.aswing.UIManager;

import com.bourre.events.BasicEvent;
import com.bourre.events.EventBroadcaster;
import com.bourre.events.EventType;

import fever.data.crypt.Crypter;
import fever.data.crypt.TEA;
import fever.display.ModalScreen;
import fever.Fever;
import fever.remoting.RemotingEventController;
import fever.remoting.RemotingEventList;
import fever.utils.StringUtil;

import fvaswing.components.login.FvRemoteLoginCommand;
import fvaswing.components.login.FvRemoteLoginResources;
import fvaswing.components.login.FvRemoteLoginVO;
import fvaswing.FvAsWing;
import fvaswing.remoting.FvAMFErrorCommand;
import fvaswing.remoting.FvSessionErrorCommand;

/**
 * Displays a dialog window with necessaries control to allow a remoting user 
 * identification.
 *
 * @author Romain Ecarnot
 */
class fvaswing.components.FvRemoteLoginDialog
{
	//-------------------------------------------------------------------------
	// Events definition
	//-------------------------------------------------------------------------
	
	/** Event type broadcasted when login identification is successfull. */
	public static var onLoginSuccessEvent : EventType = new EventType( "onLoginSuccess" );
	
	/** Event type broadcasted when login identification failed. */
	public static var onLoginErrorEvent : EventType = new EventType( "onRemoteLoginError" );
	
		
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : FvRemoteLoginDialog;
	
	private var _command : FvRemoteLoginCommand;
	
	private var _frame : JFrame;
	private var _modal : ModalScreen;
	
	private var _lblUser : JLabel;
	private var _lblPass : JLabel;
	private var _inputUser : JTextField;
	private var _inputPass : JTextField;
	private var _checkSave : JCheckBox;
	private var _okButton : JButton;
	
	private var _labelWidth : Number;
	private var _inputWidth : Number;
	
	private var _opened : Boolean;
	private var _oEB : EventBroadcaster;
	
	private var _inputLAFColor : ASColor;
	private var _inputBADColor : ASColor;
	
	private var _crypter : Crypter;
	
	
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
		
	/** Property name identifier for sharedObject saving. */
	public static function get CONFIG_ID() : String { return ".access"; };
	
	public static var SERVICE : String;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@link FvRemoteLoginDialog} instance.
	 * 
	 * <p>Always returns the same instance.<br />
	 * Design Pattern Singleton.
	 * @return {@link FvRemoteLoginDialog} instance
	 */
	public static function getInstance() : FvRemoteLoginDialog
	{
		if( !_instance ) _instance = new FvRemoteLoginDialog();
		return _instance;	
	}
	
	/**
	 * Adds passed-in {@code listener} for receiving passed-in {@code type} event type.
	 * 
	 * @param type Name of the Event.
	 * @param listener Listener object.
	 */
	public function addEventListener( type : String, listener ) : Void
	{
		_oEB.addEventListener.apply( _oEB, arguments );
	}
	
	/**
	 * Removes passed-in {@code listener} listener that suscribed for passed-in {@code type} event.
	 * 
	 * @param type Name of the Event.
	 * @param listener Listener object.
	 */
	public function removeEventListener( type : String, listener  ) : Void
	{
		_oEB.removeEventListener( type, listener );
	}
	
	/**
	 * Call by remoting login process.
	 */
	public function onConnect( b : Boolean ) : Void
	{
		var type : EventType;
		
		if( b )
		{
			type = onLoginSuccessEvent;
			_handleClose();
		}
		else
		{
			type = onLoginErrorEvent;
			_frame.setTitle( FvRemoteLoginResources.getInstance().failure );	
		}
		
		_oEB.broadcastEvent( new BasicEvent( type, this ) );
	}
	
	/**
	 * Open chooser dialog
	 */
	public function open() : Void
	{
		if( _opened ) return;
		
		_opened = true;
		
		_createUI();
		_layout();
		_updateLocalisation();
		_modal.show();
		
		var o : Object = Fever.application.config.load( FvRemoteLoginDialog.CONFIG_ID );
		var user : String = o.user;
		var pass : String = _crypter.decrypt( o.pwd, Fever.application.name );
		var save : Boolean = o.save;
		
		if( user ) _inputUser.setText( user );
		if( pass ) _inputPass.setText( pass );
		_checkSave.setSelected( save );
		
		_frame.show();
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	private function FvRemoteLoginDialog()
	{
		_opened = false;
		_labelWidth = 100;
		_inputWidth = 150;
		
		_oEB = new EventBroadcaster( this );
		
		FvAsWing.getInstance();
		
		RemotingEventController.getInstance().push( RemotingEventList.AMF_ERROR, FvAMFErrorCommand.getInstance() );
		RemotingEventController.getInstance().push( RemotingEventList.SESSION_EXPIRED, FvSessionErrorCommand.getInstance() );
		
		_command = new FvRemoteLoginCommand();
		_crypter = new Crypter( TEA.getProcess() );
		
		_inputLAFColor = UIManager.getColor( "TextField.background" );
		_inputBADColor = new ASColor( 0xD70000, 100 );
	}
	
	/**
	 * Configures the based {@code JFrame} container.
	 */
	private function _createUI() : Void
	{
		_modal = new ModalScreen( 0x000000, 0 );
		
		_frame = new JFrame( _modal.getModalTarget(), "", false );
		_frame.setResizable( false );
		_frame.setClosable( false );
		_frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
		_frame.addEventListener( JFrame.ON_WINDOW_CLOSING, _handleClose, this );
		
		_configureUI();
	}
	
	/**
	 * Prepares alert UI.
	 */
	private function _configureUI() : Void
	{
		var p : JPanel = new JPanel( new SoftBoxLayout( SoftBoxLayout.Y_AXIS, 5 ) );
		p.setBorder( new EmptyBorder( null, new Insets( 5, 5, 5, 5 ) ) );
		p.append( _getUserLine() );
		p.append( _getPassLine() );
		p.append( _getCheckLine() );
		p.append( _getButtonLine() );
		
		_updateLocalisation();
		p.revalidateIfNecessary();
		
		_frame.getContentPane().append ( p );
		_frame.pack();
	}
	
	/**
	 * Returns user label / input line container 
	 */
	private function _getUserLine() : JPanel 
	{
		_lblUser = _createLabel( "" );
		_inputUser = _createInput();
		
		var p : JPanel = new JPanel( new BorderLayout( 5,5 ) );
		p.append( _lblUser, BorderLayout.WEST );
		p.append( _inputUser, BorderLayout.CENTER );
		return p;
	}
	
	/**
	 * Returns pass label / input line container 
	 */
	private function _getPassLine() : JPanel 
	{
		_lblPass = _createLabel( "");
		_inputPass = _createInput();
		_inputPass.setPasswordField( true );
		
		var p : JPanel = new JPanel( new BorderLayout( 5,5 ) );
		p.append( _lblPass, BorderLayout.WEST );
		p.append( _inputPass, BorderLayout.CENTER );
		return p;
	}
	
	/**
	 * Returns checkbox line container 
	 */
	private function _getCheckLine() : JPanel 
	{
		_checkSave = new JCheckBox( "" );
		
		var p : JPanel = new JPanel( new BorderLayout( 5,5 ) );
		p.append( _checkSave, BorderLayout.WEST );
		return p;
	}
	
	/**
	 * Returns button line container 
	 */
	private function _getButtonLine() : JPanel 
	{
		_okButton = new JButton( "ok" );
		_okButton.addActionListener( _handleButton, this );
		
		var p : JPanel = new JPanel( new BorderLayout( 5,5 ) );
		p.append( _okButton, BorderLayout.CENTER );
		return p;
	}
	
	/**
	 * Returns a default label component.
	 */
	private function _createLabel( str : String ) : JLabel
	{
		var l : JLabel = new JLabel( str, JLabel.LEFT );
		l.setPreferredWidth( _labelWidth );
		return l;
	}
	
	/**
	 * Returns a default textfield component.
	 */
	private function _createInput( ) : JTextField
	{
		var t : JTextField = new JTextField();
		t.setPreferredWidth( _inputWidth );
		t.addActionListener( _handleButton, this );
		return t;
	}
	
	/**
	 * Calculates a new layout according message, icon and buttons 
	 * definition.
	 */
	private function _layout() : Void
	{
		var location : Point = ASWingUtils.getScreenCenterPosition();
		
		location.x -= _frame.getWidth()/2;
		location.y -= _frame.getHeight()/2;
		_frame.setLocation( location );
	}
	
	private function _updateLocalisation() : Void
	{
		_lblUser.setText( FvRemoteLoginResources.getInstance().user );			_lblPass.setText( FvRemoteLoginResources.getInstance().pwd );			_okButton.setText( FvRemoteLoginResources.getInstance().okLabel );			_checkSave.setText( FvRemoteLoginResources.getInstance().saveLabel );
		_frame.setTitle( FvRemoteLoginResources.getInstance().title );	
	}
	
	/**
	 * Trigerred when dialog is closed.
	 */
	private function _handleClose( button : JButton ) : Void
	{
		_modal.dispose();
		
		_frame.removeAll();
		_frame.tryToClose();
		
		_frame = null;
		_modal = null;
		
		delete _frame;
		delete _modal;
		
		_opened = false;
	}
	
	/**
	 * Trigerred when user click on 'ok' button
	 */
	private function _handleButton() : Void
	{
		var user : String = StringUtil.trim( _inputUser.getText() );
		var pass : String = StringUtil.trim( _inputPass.getText() );
		
		_inputUser.setBackground( ( user.length ) ? _inputLAFColor : _inputBADColor ); 
		_inputPass.setBackground( ( pass.length ) ? _inputLAFColor : _inputBADColor ); 
		
		if( user.length && pass.length )
			_command.execute( new FvRemoteLoginVO( user, pass, _checkSave.isSelected() ) );
	}
}